package com.huawei.Galenus.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huawei.Galenus.domain.Message;
import com.huawei.Galenus.domain.Song;
import com.huawei.Galenus.domain.Song1;
import com.huawei.Galenus.service.FabricService;
import com.huawei.Galenus.service.SongService;
import com.huawei.Galenus.service.UserSongService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/song")
@CrossOrigin
@Api("歌曲相关api")
public class SongController {

    @Autowired
    private SongService songService;

    @Autowired
    private FabricService fabricService;

    @Autowired
    private UserSongService userSongService;

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    private Logger logger = LoggerFactory.getLogger(UploadController.class);

    @ApiOperation("上传歌曲")
    @PostMapping("/upload")
    public Message upload(@RequestParam("songfilepath")String songfilepath,@RequestBody Song song) {
        String id = UUID.randomUUID().toString();
        System.out.println(id);
        song.setId(id);
        String method = "acsong";
        JSONObject jsonObject = (JSONObject) JSON.toJSON(song);
        String[] params = new String[]{jsonObject.toJSONString()};
        JSONObject payload = fabricService.songInvoke(method, params);
        if (payload.getString("wrong_msg") == null) {
            Song1 song1 = new Song1();
            song1.setId(id);
            song1.setName(song.getName());
            song1.setCreator(song.getCreator());
            song1.setSongfilepath(songfilepath);
            Boolean flag = songService.save(song1);
            return new Message().ok(6666, "上传成功").addData("id", id);
        } else {
            return new Message().ok(1111, "上传失败").addData("payload", payload);
        }
    }

    @ApiOperation("获取歌曲详情")
    @GetMapping("getOne")
    public Message getOne(@ApiParam("歌曲")@RequestParam("sid") String sid) {
        String method = "gsdetail";
        String[] params = new String[]{sid};
        JSONObject payload = fabricService.songQuery(method, params);
        if (payload.getString("wrong_msg") == null) {
            return new Message().ok(6666, "获取成功").addData("payload", payload);
        } else {
            return new Message().ok(1111, "获取失败").addData("payload", payload);
        }
    }

    @ApiOperation("获取歌曲")
    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> download(@ApiParam("歌曲ID") @RequestParam("sid") String sid) {
        Song1 song = songService.getById(sid);
        String musicFilePath = song.getSongfilepath();
        File file = new File(musicFilePath);
        return export(file);
    }

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

    @ApiOperation("购买歌曲")
    @PostMapping("/buy")
    @Transactional
    public Message fbsong(@ApiParam("用户ID") @RequestParam("uid") String uid, @ApiParam("歌曲ID") @RequestParam("sid") String sid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", uid);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("id", sid);
        String[] params = new String[]{jsonObject.toJSONString(), jsonObject1.toJSONString()};
        String method = "fbsong";
        JSONObject payload = fabricService.songInvoke(method, params);
        if (payload.getString("wrong_msg") == null) {
            return new Message().ok(6666, "购买成功").addData("payload", payload);
        } else {
            return new Message().ok(1111, "购买失败").addData("payload", payload);
        }
    }

    @ApiOperation("查询所有歌曲")
    @GetMapping("/all_songs")
    public Message getAllSongs() {
        List<Song1> songs = songService.getAllSongs();
        return new Message().ok(6666, "获取成功").addData("songs", songs);
    }

    @ApiOperation("查询我购买的歌曲")
    @GetMapping("/my_bought")
    public Message getMyBought(@RequestParam("uid") String uid) {
        String[] params = new String[]{uid};
        String method = "quinfo";
        JSONObject payload = fabricService.songQuery(method, params);
        JSONArray iboughtsongs = payload.getJSONArray("iboughtsongs");
        if (iboughtsongs != null) {
            List<String> list = JSONObject.parseArray(iboughtsongs.toString(), String.class);
            List<Song1> song1s = new ArrayList<>();
            for (String id : list) {
                Song1 song1 = songService.getById(id);
                song1s.add(song1);
            }
            return new Message().ok(6666, "查询成功").addData("songs", song1s);
        } else {
            return new Message().ok(6666, "暂无歌曲").addData("songs", null);
        }
    }

    @ApiOperation("查询我上传的歌曲")
    @GetMapping("/my_upload")
    public Message getMyUpload(@RequestParam("uid") String uid) {
        String[] params = new String[]{uid};
        String method = "quinfo";
        JSONObject payload = fabricService.songQuery(method, params);
        JSONArray mysongs = payload.getJSONArray("mysongs");
        if (mysongs != null) {
            List<String> list = JSONObject.parseArray(mysongs.toString(), String.class);
            List<Song1> song1s = new ArrayList<>();
            for (String id : list) {
                Song1 song1 = songService.getById(id);
                song1s.add(song1);
            }
            return new Message().ok(6666, "查询成功").addData("songs", song1s);
        } else {
            return new Message().ok(6666, "暂无歌曲").addData("songs", null);
        }
    }

    @ApiOperation("修改歌曲价格")
    @PutMapping("/esprice")
    public Message esprice(@RequestParam("sid") String sid, @RequestParam("newPrice") int newPrice) {
        String[] params = new String[]{sid, newPrice + ""};
        String method = "esprice";
        JSONObject payload = fabricService.songInvoke(method, params);
        if (payload.getString("wrong_msg") == null) {
            return new Message().ok(6666, "修改成功").addData("payload", payload);
        } else {
            return new Message().ok(1111, "修改失败").addData("payload", payload);
        }
    }

    @ApiOperation("修改歌曲授权价格")
    @PutMapping("/eaprice")
    public Message eaprice(@RequestParam("sid") String sid, @RequestParam("newPrice") int newPrice) {
        String[] params = new String[]{sid, newPrice + ""};
        String method = "eaprice";
        JSONObject payload = fabricService.songInvoke(method, params);
        if (payload.getString("wrong_msg") == null) {
            return new Message().ok(6666, "修改成功").addData("payload", payload);
        } else {
            return new Message().ok(1111, "修改失败").addData("payload", payload);
        }
    }
}
